{
 "cells": [
  {
   "cell_type": "code",
   "id": "22a97a3a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:50:15.859496Z",
     "start_time": "2025-05-15T12:50:15.588346Z"
    }
   },
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "id": "c3bebf6d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:50:15.978097Z",
     "start_time": "2025-05-15T12:50:15.967511Z"
    }
   },
   "source": [
    "features = ['accommodates', 'bedrooms', 'bathrooms', 'beds', 'price', 'minimum_nights','maximum_nights', 'number_of_review']\n",
    "dc_listings = pd.read_csv('../CSV/listing.csv')\n",
    "dc_listings = dc_listings[features]"
   ],
   "outputs": [],
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "id": "365492fd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:50:32.629220Z",
     "start_time": "2025-05-15T12:50:32.556849Z"
    }
   },
   "source": [
    "dc_listings.drop('distance', axis=1)\n",
    "test_df = dc_listings.copy().iloc[:200]\n",
    "test_df = dc_listings.iloc[200:]\n",
    "\n",
    "def predict_price(new_listing):\n",
    "    temp_df = dc_listings[dc_listings.feature_column!= new_listing.column]\n",
    "    temp_df = temp_df.sort_values('distance')\n",
    "    knn_5 = temp_df.iloc[:5]\n",
    "    predicted_price = knn_5.price.mean()\n",
    "    return predicted_price\n",
    "\n",
    "test_df['predicted_price'] = test_df.accommodates.apply(predict_price, feature_columns=['accommodates'])\n"
   ],
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "\"['distance'] not found in axis\"",
     "output_type": "error",
     "traceback": [
      "\u001B[31m---------------------------------------------------------------------------\u001B[39m",
      "\u001B[31mKeyError\u001B[39m                                  Traceback (most recent call last)",
      "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[5]\u001B[39m\u001B[32m, line 1\u001B[39m\n\u001B[32m----> \u001B[39m\u001B[32m1\u001B[39m \u001B[43mdc_listings\u001B[49m\u001B[43m.\u001B[49m\u001B[43mdrop\u001B[49m\u001B[43m(\u001B[49m\u001B[33;43m'\u001B[39;49m\u001B[33;43mdistance\u001B[39;49m\u001B[33;43m'\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43maxis\u001B[49m\u001B[43m=\u001B[49m\u001B[32;43m1\u001B[39;49m\u001B[43m)\u001B[49m\n\u001B[32m      2\u001B[39m test_df = dc_listings.copy().iloc[:\u001B[32m200\u001B[39m]\n\u001B[32m      3\u001B[39m test_df = dc_listings.iloc[\u001B[32m200\u001B[39m:]\n",
      "\u001B[36mFile \u001B[39m\u001B[32mP:\\Python\\Python_DataAnalyze\\Lib\\site-packages\\pandas\\core\\frame.py:5581\u001B[39m, in \u001B[36mDataFrame.drop\u001B[39m\u001B[34m(self, labels, axis, index, columns, level, inplace, errors)\u001B[39m\n\u001B[32m   5433\u001B[39m \u001B[38;5;28;01mdef\u001B[39;00m\u001B[38;5;250m \u001B[39m\u001B[34mdrop\u001B[39m(\n\u001B[32m   5434\u001B[39m     \u001B[38;5;28mself\u001B[39m,\n\u001B[32m   5435\u001B[39m     labels: IndexLabel | \u001B[38;5;28;01mNone\u001B[39;00m = \u001B[38;5;28;01mNone\u001B[39;00m,\n\u001B[32m   (...)\u001B[39m\u001B[32m   5442\u001B[39m     errors: IgnoreRaise = \u001B[33m\"\u001B[39m\u001B[33mraise\u001B[39m\u001B[33m\"\u001B[39m,\n\u001B[32m   5443\u001B[39m ) -> DataFrame | \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[32m   5444\u001B[39m \u001B[38;5;250m    \u001B[39m\u001B[33;03m\"\"\"\u001B[39;00m\n\u001B[32m   5445\u001B[39m \u001B[33;03m    Drop specified labels from rows or columns.\u001B[39;00m\n\u001B[32m   5446\u001B[39m \n\u001B[32m   (...)\u001B[39m\u001B[32m   5579\u001B[39m \u001B[33;03m            weight  1.0     0.8\u001B[39;00m\n\u001B[32m   5580\u001B[39m \u001B[33;03m    \"\"\"\u001B[39;00m\n\u001B[32m-> \u001B[39m\u001B[32m5581\u001B[39m     \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43msuper\u001B[39;49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\u001B[43m.\u001B[49m\u001B[43mdrop\u001B[49m\u001B[43m(\u001B[49m\n\u001B[32m   5582\u001B[39m \u001B[43m        \u001B[49m\u001B[43mlabels\u001B[49m\u001B[43m=\u001B[49m\u001B[43mlabels\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5583\u001B[39m \u001B[43m        \u001B[49m\u001B[43maxis\u001B[49m\u001B[43m=\u001B[49m\u001B[43maxis\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5584\u001B[39m \u001B[43m        \u001B[49m\u001B[43mindex\u001B[49m\u001B[43m=\u001B[49m\u001B[43mindex\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5585\u001B[39m \u001B[43m        \u001B[49m\u001B[43mcolumns\u001B[49m\u001B[43m=\u001B[49m\u001B[43mcolumns\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5586\u001B[39m \u001B[43m        \u001B[49m\u001B[43mlevel\u001B[49m\u001B[43m=\u001B[49m\u001B[43mlevel\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5587\u001B[39m \u001B[43m        \u001B[49m\u001B[43minplace\u001B[49m\u001B[43m=\u001B[49m\u001B[43minplace\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5588\u001B[39m \u001B[43m        \u001B[49m\u001B[43merrors\u001B[49m\u001B[43m=\u001B[49m\u001B[43merrors\u001B[49m\u001B[43m,\u001B[49m\n\u001B[32m   5589\u001B[39m \u001B[43m    \u001B[49m\u001B[43m)\u001B[49m\n",
      "\u001B[36mFile \u001B[39m\u001B[32mP:\\Python\\Python_DataAnalyze\\Lib\\site-packages\\pandas\\core\\generic.py:4788\u001B[39m, in \u001B[36mNDFrame.drop\u001B[39m\u001B[34m(self, labels, axis, index, columns, level, inplace, errors)\u001B[39m\n\u001B[32m   4786\u001B[39m \u001B[38;5;28;01mfor\u001B[39;00m axis, labels \u001B[38;5;129;01min\u001B[39;00m axes.items():\n\u001B[32m   4787\u001B[39m     \u001B[38;5;28;01mif\u001B[39;00m labels \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[32m-> \u001B[39m\u001B[32m4788\u001B[39m         obj = \u001B[43mobj\u001B[49m\u001B[43m.\u001B[49m\u001B[43m_drop_axis\u001B[49m\u001B[43m(\u001B[49m\u001B[43mlabels\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43maxis\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mlevel\u001B[49m\u001B[43m=\u001B[49m\u001B[43mlevel\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43merrors\u001B[49m\u001B[43m=\u001B[49m\u001B[43merrors\u001B[49m\u001B[43m)\u001B[49m\n\u001B[32m   4790\u001B[39m \u001B[38;5;28;01mif\u001B[39;00m inplace:\n\u001B[32m   4791\u001B[39m     \u001B[38;5;28mself\u001B[39m._update_inplace(obj)\n",
      "\u001B[36mFile \u001B[39m\u001B[32mP:\\Python\\Python_DataAnalyze\\Lib\\site-packages\\pandas\\core\\generic.py:4830\u001B[39m, in \u001B[36mNDFrame._drop_axis\u001B[39m\u001B[34m(self, labels, axis, level, errors, only_slice)\u001B[39m\n\u001B[32m   4828\u001B[39m         new_axis = axis.drop(labels, level=level, errors=errors)\n\u001B[32m   4829\u001B[39m     \u001B[38;5;28;01melse\u001B[39;00m:\n\u001B[32m-> \u001B[39m\u001B[32m4830\u001B[39m         new_axis = \u001B[43maxis\u001B[49m\u001B[43m.\u001B[49m\u001B[43mdrop\u001B[49m\u001B[43m(\u001B[49m\u001B[43mlabels\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43merrors\u001B[49m\u001B[43m=\u001B[49m\u001B[43merrors\u001B[49m\u001B[43m)\u001B[49m\n\u001B[32m   4831\u001B[39m     indexer = axis.get_indexer(new_axis)\n\u001B[32m   4833\u001B[39m \u001B[38;5;66;03m# Case for non-unique axis\u001B[39;00m\n\u001B[32m   4834\u001B[39m \u001B[38;5;28;01melse\u001B[39;00m:\n",
      "\u001B[36mFile \u001B[39m\u001B[32mP:\\Python\\Python_DataAnalyze\\Lib\\site-packages\\pandas\\core\\indexes\\base.py:7070\u001B[39m, in \u001B[36mIndex.drop\u001B[39m\u001B[34m(self, labels, errors)\u001B[39m\n\u001B[32m   7068\u001B[39m \u001B[38;5;28;01mif\u001B[39;00m mask.any():\n\u001B[32m   7069\u001B[39m     \u001B[38;5;28;01mif\u001B[39;00m errors != \u001B[33m\"\u001B[39m\u001B[33mignore\u001B[39m\u001B[33m\"\u001B[39m:\n\u001B[32m-> \u001B[39m\u001B[32m7070\u001B[39m         \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;167;01mKeyError\u001B[39;00m(\u001B[33mf\u001B[39m\u001B[33m\"\u001B[39m\u001B[38;5;132;01m{\u001B[39;00mlabels[mask].tolist()\u001B[38;5;132;01m}\u001B[39;00m\u001B[33m not found in axis\u001B[39m\u001B[33m\"\u001B[39m)\n\u001B[32m   7071\u001B[39m     indexer = indexer[~mask]\n\u001B[32m   7072\u001B[39m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28mself\u001B[39m.delete(indexer)\n",
      "\u001B[31mKeyError\u001B[39m: \"['distance'] not found in axis\""
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "cell_type": "markdown",
   "id": "c8b7c334",
   "metadata": {},
   "source": " rmse对异常值更敏感"
  },
  {
   "cell_type": "code",
   "id": "0488c1d1",
   "metadata": {},
   "source": [
    "test_df['squared_error'] = (test_df['predicted_price'] - test_df['price'])**(2)\n",
    "mse = test_df['squared_error'].mean()\n",
    "rmse = mse**(1/2)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "id": "0afffcdb",
   "metadata": {},
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "features = ['accommodates', 'bedrooms', 'bathrooms', 'beds', 'price','minimum_nights','maximum_nights', 'number_of_reviews']\n",
    "dc_listings = pd.read_csv('listing.csv')\n",
    "dc_listings = dc_listings[features]\n",
    "n\n",
    "dc_listings['distance'] = np.abs(dc_listings['accommodates'] - 3)\n",
    "\n",
    "train_df = dc_listings.iloc[:2799]\n",
    "test_df = dc_listings.iloc[2799:]\n",
    "\n",
    "def predict_price(new_listing):\n",
    "    temp_df = train_df[train_df['accommodates'] != new_listing['accommodates']]\n",
    "    temp_df = temp_df.sort_values('distance')\n",
    "    knn_5 = temp_df.iloc[:5]\n",
    "    predicted_price = knn_5['price'].mean()\n",
    "    return predicted_price\n",
    "\n",
    "test_df['predicted_price'] = test_df.apply(predict_price, axis=1)\n",
    "\n",
    "mse = np.mean((test_df['price'] - test_df['predicted_price']) ** 2)\n",
    "rmse = np.sqrt(mse)\n",
    "print(f\"均方误差（MSE）: {mse}\")\n",
    "print(f\"均方根误差（RMSE）: {rmse}\")\n"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "gpt生成代码",
   "id": "60d2778eab82b9e6"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-15T12:50:16.845804200Z",
     "start_time": "2025-05-15T00:08:09.418717Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# 读取数据并选择特征\n",
    "features = ['accommodates', 'bedrooms', 'bathrooms', 'beds', 'price', 'minimum_nights', 'maximum_nights', 'number_of_review']\n",
    "dc_listings = pd.read_csv('listing.csv')\n",
    "dc_listings = dc_listings[features]\n",
    "\n",
    "# 划分训练集和测试集\n",
    "train_df = dc_listings.iloc[:200].copy()\n",
    "test_df = dc_listings.iloc[200:].copy()\n",
    "\n",
    "# 定义预测函数，基于 accommodates 计算距离\n",
    "def predict_price(new_value):\n",
    "    temp_df = train_df.copy()\n",
    "    # 创建 distance 列：表示当前样本与训练集中其他样本的“accommodates”差异\n",
    "    temp_df['distance'] = np.abs(temp_df['accommodates'] - new_value)\n",
    "    # 按距离排序，取前5个最近邻\n",
    "    knn_5 = temp_df.sort_values('distance').iloc[:5]\n",
    "    # 计算平均价格作为预测值\n",
    "    return knn_5['price'].mean()\n",
    "\n",
    "# 应用预测函数\n",
    "test_df['predicted_price'] = test_df['accommodates'].apply(predict_price)"
   ],
   "id": "be2910b7491fd457",
   "outputs": [],
   "execution_count": 13
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
